<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.categoryName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入分类名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
          stripe
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          row-key="id"
          :tree-props="{ children: 'children' }"
          :row-class-name="rowClassName">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="categoryName" label="分类名称">
          <template v-slot="scope">
            <span style="cursor: pointer; color: #409EFF">
              {{ scope.row.categoryName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="分类描述" />
        <el-table-column label="分类图片" width="150">
          <template v-slot="scope">
            <img v-if="scope.row.categoryImg" :src="scope.row.categoryImg" alt="分类图片" style="width: 100px; height: 60px; object-fit: cover;" />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUsername" label="创建者" />
        <el-table-column prop="updateUsername" label="更新者" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <el-dialog title="分类信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="categoryName" label="分类名称">
          <el-input v-model="data.form.categoryName" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="分类描述">
          <el-input v-model="data.form.description" placeholder="请输入分类描述"></el-input>
        </el-form-item>
        <el-form-item label="分类图片">
          <el-input v-model="data.form.categoryImg" placeholder="请输入分类图片URL"></el-input>
        </el-form-item>
        <el-form-item prop="parentId" label="父类">
          <el-select v-model="data.form.parentId" placeholder="请选择父类" clearable>
            <el-option :value="''" label="无父类" />
            <el-option
                v-for="item in data.allCategories"
                :key="item.id"
                :label="item.categoryName"
                :value="String(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建者">
          <el-input v-model="data.form.createUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新者">
          <el-input v-model="data.form.updateUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="data.form.createdAt" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="data.form.updatedAt" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";

const data = reactive({
  formVisible: false,
  form: {
    parentId: '' // 初始化父类ID为空字符串
  },
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  categoryName: null,
  ids: [],
  allCategories: []
});

const rowClassName = ({ row }) => {
  return row.parentId ? 'child-row' : 'parent-row';
};

const load = () => {
  request.get('/plantClass/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      categoryName: data.categoryName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    }
  });
};

const loadAllCategories = () => {
  request.get('/plantClass/selectAll').then(res => {
    if (res.code === '200') {
      data.allCategories = res.data;
      console.log(res.data)
    }
  });
};

const handleAdd = () => {
  data.form = {
    parentId: '' // 初始化父类ID为空字符串
  };
  data.formVisible = true;
};

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.form.parentId = data.form.parentId !== null ? String(data.form.parentId) : ''; // 确保parentId是字符串
  data.formVisible = true;
};

const save = () => {
  const formData = { ...data.form };
  formData.parentId = formData.parentId === '' ? null : formData.parentId; // 将空字符串转换为null
  formData.id ? update(formData) : add(formData);
};

const add = (formData) => {
  request.post('/plantClass/add', formData).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = (formData) => {
  request.put('/plantClass/update', formData).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/plantClass/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete("/plantClass/delete/batch", { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

const reset = () => {
  data.categoryName = null;
  load();
};

onMounted(() => {
  load();
  loadAllCategories();
});
</script>

<style scoped>
.parent-row {
  background: #f8f8f9;
}

.child-row td:first-child .cell {
  padding-left: 40px !important;
}

:deep(.el-table__expand-icon) {
  cursor: pointer;
}
</style>



